<?php

namespace Admin\Controller;

use Base\BackController;

//上传一张普通图片，调用阿里云接口进行抠图
class ImageMattingController extends BackController {

    public function _initialize() {
        parent::_initialize();
        $this->imgSubFolder=1502294400; //20170810
    }

    //页面初始显示
    public function index() {
        
        $this->display();
    }
    

    //上传待去背图片
    public function uploadImg() {
        
       try {
            //导入上传类
            $upload = new \Admin\ORG\UploadFileNew();
            //设置上传文件大小
            $upload->maxSize            = 100*1024*1024;
            //设置上传文件类型
            $upload->allowExts          = explode(',', 'jpg,gif,png,jpeg');
            //设置附件上传目录
            $upload->savePath           = ic_getUploadImgServerPath('test',$this->imgSubFolder);
            //设置需要生成缩略图，仅对图像文件有效
            $upload->thumb              = true;
            // 设置引用图片类库包路径
            $upload->imageClassPath     = 'Think.ImageNew';
            //设置需要生成缩略图的文件后缀
            $upload->thumbPrefix        = 'm_,s_';  //生产2张缩略图
            //设置缩略图最大宽度
            $upload->thumbMaxWidth      = '700,200';
            //设置缩略图最大高度
            $upload->thumbMaxHeight     = '850,243';
            //设置上传文件规则
            $upload->saveRule           = 'uniqid';
            //删除原图
            $upload->thumbRemoveOrigin  = false;
            if (!$upload->upload()) {
                //捕获上传异常
                //$this->error($upload->getErrorMsg());
                //echo ($upload->getErrorMsg());
            } else {

                //取得成功上传的文件信息
                $uploadList = $upload->getUploadFileInfo();
                //试着删除之前上传的旧图片
                $this->deleteOld();
                //保存当前图片信息到session
                $this->saveOldFIleSession($uploadList,$this->imgSubFolder);
                foreach ($uploadList as $key => $value) {
                    echo "<script>
                    parent.document.getElementById('img').style.display='';
                    parent.document.getElementById('img').src='" . ic_getUploadImgFullPath('test',$value['savename'],$this->imgSubFolder) . "';
                    parent.document.getElementById('p_new_pic').value='" . $value['savename'] . "';
                    </script>";
                    
                }   
            }
           
        }catch (Exception $exc) {
            //返回失败信息
            echo "<script>parent.art.dialog.alert('" . $exc->getMessage() . "');</script>";
            exit;
        }
    }

    //https://market.console.aliyun.com/imageconsole/index.htm?spm=5176.7744816.2.1.4JILYr#/bizlist?_k=dhts2d
    //AppCode：310ed976487b42de9ed19368b753cd38
    //AppKey：24580288     AppSecret：16a934fe8b23d14cd9589fa54ae22d08
    public function matt_image(){
        $img_name=I('img_name');
        ///DEBUG
        // $img_name="IMG_4263.JPG";
        // $img_name="sample.png";
        ///ENDDEBUG
        $serverPath=ic_getUploadImgServerPath("test",$this->imgSubFolder);
        $imgBase64=$this->getImageBase64($serverPath."m_".$img_name);
        ///DEBUG
        // $this->customReturn(1,$imgBase64);
        ///END DEBUG
        $re = $this->callMattingApi($imgBase64);
        $succ=0;
        $reArr=json_decode($re,true);

        if($reArr){
            if(array_key_exists("result", $reArr)){
                if(array_key_exists("resultCode", $reArr['result'])){
                    if($reArr['result']['resultCode']==1){
                        $re=$reArr['result']['resultObject'];
                        $succ=1;
                    }
                }
            }
        }
        $this->customReturn($succ,$re);
    }

    private function callMattingApi($imgBase64) {
        $host = "https://dm-71.data.aliyun.com";
        $path = "/rest/160601/int_image/matting.json";
        $method = "POST";
        $appcode = "310ed976487b42de9ed19368b753cd38";
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type".":"."application/json; charset=UTF-8");
        // array_push($headers, "X-Ca-Request-Mode".":"."debug");
        // array_push($headers, "X-Ca-Stage".":"."TEST");
        $querys = "";
        $bodys = '{"image": {"dataType": 10, "dataValue": "'.$imgBase64.'"}}';
        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$".$host, "https://"))
        {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
            // dump('no ssl');
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        ///DEBUG
        // dump($url);
        // dump($headers);
        // dump($bodys);
        $re = (curl_exec($curl));
        curl_close($curl);
        
        return $re;

    }
    //读取图片文件，转换成base64编码格式
    private function getImageBase64($imgFullPath){
        $image_info = getimagesize($imgFullPath);
        // $base64_image_content = "data:{$image_info['mime']};base64," . (base64_encode(file_get_contents($imgFullPath)));
        $base64_image_content = "". (base64_encode(file_get_contents($imgFullPath)));
        return $base64_image_content;
    }

    private function delMulti($serverPath,$delName){
        @unlink($serverPath.$delName);
        @unlink($serverPath."m_".$delName);
        @unlink($serverPath."s_".$delName);
    }

    //从session取得旧图片信息并删除
    private function deleteOld(){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $oldFiles=$_SESSION[$skey];
        if(!$oldFiles){
            return;
        }
        foreach ($oldFiles as $key => $value) {
            $serverPath=ic_getUploadImgServerPath("test",$_SESSION[$skey."_time"]);
            // @unlink($serverPath.$value['savename']);
            // @unlink($serverPath."m_".$value['savename']);
            // @unlink($serverPath."s_".$value['savename']);
            $this->delMulti($serverPath,$value['savename']);
        }
    }

    private function saveOldFIleSession($arr,$ctime){
        $skey=I('session_key',false);
        if($skey===false){
            return;
        }
        $_SESSION[$skey]=$arr;
        $_SESSION[$skey."_time"]=$ctime;
    }

    public function getMillisecond() {
        list($t1, $t2) = explode(' ', microtime());
        return (float) sprintf('%.0f', (floatval($t1) + floatval($t2)) * 1000);
    }
    
}
